package com.hqyj.freemovie.front.controller;

import com.hqyj.freemovie.front.view.Students;
import com.hqyj.freemovie.front.json.R;
import com.hqyj.freemovie.front.repository.StudentsRepository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

@RestController
@RequestMapping("students")
public class StudentsController extends BaseController{

    @Resource
    private StudentsRepository studentsRepository;


    //@PostMapping("/{id}")
    @PostMapping("/")
    public R saveStudents(@RequestBody Students students) {
        try {
            Students s = studentsRepository.save(students);
            return R.success("保存学生资料成功！", s);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }


    @GetMapping("/{sid}")
    public R queryStudentBySid(@PathVariable("sid") String sid){
        try{
            Optional<Students> optional = studentsRepository.findById(sid);
            return optional.map(students -> R.success("查询学生资料成功！", students)).orElseGet(() -> R.fail("查询学生资料失败！"));

        }catch(Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }
}
